import fs from 'fs'
import path from 'path'
import { Dispatch } from '../reducers/types'
export const SELECT_FILE = 'SELECT_FILE'


import { save_xml, save_python } from '../../file/file'
// fs.watch(save_xml, { encoding: 'buffer' }, (eventType, filename) => {
//   console.log(eventType)
//   if (filename) {
//     console.log(filename);
//   }
// })

async function mycall() {
  const files: string[] = []
  const dir = await fs.promises.opendir(save_xml);
  for await (const dirent of dir) {
    files.push(dirent.name.slice(0, dirent.name.length - 4))
  }
  return files
}

export const select = () => async (dispatch: Dispatch) => {
  const files = await mycall()
  dispatch({ type: SELECT_FILE, data: files })
}

export const add = (name: string) => async (dispatch: Dispatch) => {
  await fs.promises.appendFile(path.join(save_xml, `${name}.xml`), '<xml></xml>')
  await fs.promises.appendFile(path.join(save_python, `${name}.py`), '')
  const files = await mycall()
  dispatch({ type: SELECT_FILE, data: files })
}

export const changeFile = (oldname: string, newname: string) => async (dispatch: Dispatch) => {
  await fs.promises.rename(path.join(save_xml, `${oldname}.xml`), path.join(save_xml, `${newname}.xml`))
  await fs.promises.rename(path.join(save_python, `${oldname}.py`), path.join(save_xml, `${newname}.py`))
  const files = await mycall()
  dispatch({ type: SELECT_FILE, data: files })
}

export const saveCode = (name: string, xml: string, py: string) => async (dispatch: Dispatch) => {
  await fs.promises.writeFile(path.join(save_xml, `${name}.xml`), xml, 'utf8');
  await fs.promises.writeFile(path.join(save_python, `${name}.py`), py, 'utf8');
  const files = await mycall()
  dispatch({ type: SELECT_FILE, data: files })
}

export const delectFile = (name: string) => async (dispatch: Dispatch) => {
  await fs.promises.unlink(path.join(save_xml, `${name}.xml`));
  await fs.promises.unlink(path.join(save_python, `${name}.py`));
  const files = await mycall()
  dispatch({ type: SELECT_FILE, data: files })
}
